package com.dtborad.myblog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dtborad.myblog.entity.Posts;
import com.dtborad.myblog.mapper.PostsMapper;
import com.dtborad.myblog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PostServiceImpl extends ServiceImpl<PostsMapper, Posts> implements PostService {
    @Autowired
    private PostsMapper postsMapper;
    @Override
    public Integer updatePostById(Posts posts) {
        try{
            System.out.println("post-----" + posts);
            //先查询文章是否存在
            LambdaQueryWrapper<Posts> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Posts::getPostid, posts.getPostid());
            Posts one = postsMapper.selectOne(queryWrapper);
            if(one != null){
                one.setCategoryid(posts.getCategoryid());
                one.setContent(posts.getContent());
                one.setTags(posts.getTags());
                one.setTitle(posts.getTitle());
                one.setPublishtime(new Date());
                one.setLikes(posts.getLikes());
                postsMapper.update(one,queryWrapper);
            }
        }catch (Exception e){
            return 1;
        }
        return 0;
    }

    //分页查询
    public Page<Posts> getAllPostsByPageSize(Integer page, Integer pageSize, Integer categoryId, String content, Integer userId) {
        LambdaQueryWrapper<Posts> wrapper = new LambdaQueryWrapper<>();
        // 根据 userId 过滤
        if (userId != null && userId != 1) {
            wrapper.eq(Posts::getAuthorid, userId);
        }

        // 根据 categoryId 过滤
        if (categoryId != null) {
            wrapper.eq(Posts::getCategoryid, categoryId);
        }

        // 根据 content 过滤
        if (StrUtil.isNotBlank(content)) {
            wrapper.like(Posts::getContent, content);
        }

        // 分页查询
        return postsMapper.selectPage(new Page<>(page, pageSize), wrapper);
    }
}
